import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useStore } from '@/hooks/store'

const modules = import.meta.glob(['../views/**/*.vue', '!../views/**/components'])

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'index',
    component: () => import('@/pages/main/index.vue'),
    children: [
      { path: '', name: 'home', component: () => import('@/views/index.vue') },
      { path: 'sys/user', name: 'sys-user', component: () => import('@/views/sys/user/index.vue') }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/pages/login/index.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    ...routes
    // ...Object.entries(modules).map(([key, value]) => {
    //   const path = key.match(/..\/views(.*)\/index.vue/)![1]
    //   return {
    //     path,
    //     component: value
    //   }
    // })
  ]
})

const whiteNames = ['login']
router.beforeEach(async (to) => {
  const { user } = useStore()

  const { token, info } = user

  if (whiteNames.includes(to.name as string)) {
    return
  }

  // 没有 token 去登录
  if (!token) {
    return { name: 'login' }
  }

  // 没有 用户信息, 获取用户信息
  if (!info) {
    await user.get()
  }
})

export default router
